package com.bifrost.authorization.resolver;

import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.entity.User;
import com.bifrost.exception.UnAuthorizationException;
import org.apache.shiro.SecurityUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Author by yanxiaobo
 * Date on 2018/4/12$.
 */
@Component
public class AdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数类型是User并且有CurrentAdmin注解则支持
        if (parameter.getParameterType().isAssignableFrom(Long.class) &&
                parameter.hasParameterAnnotation(CurrentAdmin.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (null == user) {
            throw new UnAuthorizationException("用户未登录");
        }
        return user.getId();
    }
}
